package com.zhisheng.filter;

import com.alibaba.fastjson.JSONObject;
import com.zhisheng.config.MyJwtProperties;
import com.zhisheng.pojo.MyResponseResult;
import com.zhisheng.utils.MyThreadLocalUtils;
import com.zhisheng.utils.MyUtilsJwt;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.json.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebFilter(urlPatterns = "/*")
 @Component
public class MyLoginFilter implements Filter {
    @Autowired
    private MyUtilsJwt myUtilsJwt;
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        //获取用户请求的资源路径，为了更多的功能，ServletRequest要换成HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI(); //获取请求的资源路径
        //request.getRequestURL();//获取请求的资源路径和参数  完整路径
        //判断请求的资源路径是否是登录页面，如果是，直接放行
        if (uri.equals("/login")){
            //登录页面，放行
            filterChain.doFilter(servletRequest,servletResponse);
            //结束当前方法，走完登录页面的代码，后面的代码就不会执行了，提前结束过滤器
            return;
        }
        //根据请求头中的token获取令牌
        String token = request.getHeader("Token");
        //验证是否合法
        Map<String,Object> map = myUtilsJwt.getClaims(token);
        if (map == null){
            //令牌不合法，不放行  ThreadLocal   线程局部变量 放进线程中
            //为了保持前后端的统一，统一响应结果对象
            MyResponseResult result = MyResponseResult.error("NOT_LOGIN");
            //把result响应给前端  由于代码还没有执行Controller，要手动转JSON，手动响应数据

            String stringJSON = JSONObject.toJSONString(result);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.getWriter().println(stringJSON);
            return;
        }
        //令牌合法，放行   把令牌中的数据放入ThreadLocal中 以便于后续使用
        MyThreadLocalUtils.setValue(map);
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
